/*
 * @Description:
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2022-12-29 10:04:18
 */
import { IKey } from '@/locale/zh-CN'
let langPackage: any = {}
/**获取语言 */
export const getLocale = () => {
  const defaultLang = 'zh-CN'
  return Tools.LocalStorage.getItem('lang') || defaultLang
}

/**初始化语言包 */
export const initLang = () => {
  //引入所有语言包并合并
  mergeLangs(import.meta.glob('@/locale/*', { eager: true }))
}

/**合并语言包 */
export const mergeLangs = (importLangFile: any) => {
  //   /src/locale/en-US.ts Module {Symbol(Symbol.toStringTag): 'Module'}
  //   /src/locale/zh-CN.ts Module {Symbol(Symbol.toStringTag): 'Module'}
  for (const path in importLangFile) {
    //判断当前应该选择哪种语言
    if (path.indexOf(getLocale()) !== -1) {
      langPackage = importLangFile[path].default
      return
    }
  }
}

/**页面使用语言包 */
const lang = (key: IKey & string, option?: { index?: number; default?: string }): string => {
  const value = langPackage[key]
  if (Array.isArray(value)) {
    return option?.default || value[option?.index || 0] || key
  }
  return value || option?.default || key
}

/**修改语言 */
export const changeLanguage = (lang: string) => {
  const LANGS = ['zh-CN', 'en-US']
  if (!LANGS.includes(lang.toLocaleLowerCase())) return
  Tools.LocalStorage.setItem('lang', lang)
  document.location.reload()
}
export type ILang = typeof lang

export default lang
